package com.netcracker.studies;

import Beans.AuthorizationBeanInterface;
import DBConnection.DBAPI;
import DBConnection.DBObject;
import DBConnection.DBTools;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigInteger;
import java.util.HashMap;

@WebServlet(name = "AccCreateServlet")
public class AccCreateServlet extends BaseServlet {
    protected void handlePostRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/plain; charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        HttpSession session = request.getSession(true);
        AuthorizationBeanInterface a = (AuthorizationBeanInterface) session.getAttribute("UserBean");
        BigInteger id = DBTools.getNewID();
        Integer number = DBTools.getNewAccNumber();
        DBObject acc = new DBObject(id, DBAPI.ACCOUNT,a.getUserLogin() + " acc", null, null, new HashMap<BigInteger, Object>());
        acc.setAttribute(DBAPI.ATTR_ACCOUNT_NUMBER, number);
        acc.setAttribute(DBAPI.ATTR_AMOUNT, 0);
        acc.setAttribute(DBAPI.ATTR_USER_ID, a.getUserId());
        DBAPI.insertObject(acc);
        response.getWriter().write("Счет создан. Номер счета: " + number);
    }

    protected void handleGetRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       // response.getWriter().write("createNewAcc.jsp");
        request.getRequestDispatcher("createNewAcc.jsp").forward(request,response);
    }
}
